<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class MoveLocalFileToOssJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;


    protected $from_driver;
    protected $to_driver;
    protected $path;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($from_driver, $to_driver, $path)
    {
        $this->from_driver = $from_driver;
        $this->to_driver = $to_driver;
        $this->path = $path;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        if ($path = $this->path) {
            $to = Storage::disk($this->to_driver);
            $from = Storage::disk($this->from_driver);
            if ($from->exists($path)) {
                try {
                    if (!$to->exists($path)) {
                        $to->put($path, $from->get($path));
                    }
                } catch (\Exception $exception) {
                    $this->writeLog($path);
                }
            } else {
                $this->writeLog($path);
            }
        }
    }

    protected function writeLog($msg)
    {
        $path = storage_path("app/backup");
        if (!is_dir($path)) {
            mkdir($path);
        }
        file_put_contents($path . '/' . date('Y-m-d') . '-error.log', $msg . "\n", FILE_APPEND);
    }

    public function failed()
    {
        Log::error($this->path . '队列任务执行失败' . "\n" . date('Y-m-d H:i:s'));
    }

}
